import axios from "axios";
import { useDispatch } from "react-redux";
import { Field, Form, Button, Switch, Notify } from "react-vant";
import { loginSuccess } from "../../store/user/userSlice";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const onFinish = async (value) => {
    if (!value.state) {
      Notify.show({
        type: "danger",
        message: "用户协议必须统一才可以登录！！",
      });
      return;
    }

    const resp = await axios.post("/api/login", value);
    const { code, data, message } = resp.data;
    if (code === 200) {
      Notify.show({
        type: "success",
        message: message,
      });
      dispatch(loginSuccess(data));
      navigate("/");
    } else {
      Notify.show({
        type: "danger",
        message: message,
      });
    }
  };
  return (
    <div>
      <Form
        onFinish={onFinish}
        footer={
          <Button type="primary" block round nativeType="submit">
            提交
          </Button>
        }
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: "用户名不可以为空" }]}
        >
          <Field></Field>
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: "密码不可以为空" }]}
        >
          <Field></Field>
        </Form.Item>
        <Form.Item
          name="state"
          label="协议"
          rules={[
            {
              validator(rule, value) {
                return new Promise((resolve, reject) => {
                  if(value === true) {
                    resolve(Promise.resolve())
                  } else {
                    reject(new Error("必须同意许可"))
                  }
                })
              },  
            },
          ]}
        > 
          <Switch></Switch>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
